package at.codebase.web.util.i18n;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.FileUtils;

import at.codebase.web.util.i18n.I18NFactory.I18NFileLoadingException;

/**
 * Represents a single language. Use the
 * {@link at.codebase.web.util.i18n.I18NFactory.i18n} method to get an cached
 * instance of a i18n file.
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 * 
 */
public class I18N {

	public static final I18NLocale DEFAULT_LANGUAGE = new I18NLocale("eng");
	private static final String I18N_FOLDER = "WEB-INF/i18n/";

	private I18NLocale language;
	private HashMap<String, String> words = new HashMap<String, String>();

	public I18N(I18NLocale lang) {
		this.language = lang;
	}

	/**
	 * Returns the translated string referring to the given key.
	 * 
	 * @param key
	 * @return the i18n string
	 */
	public String string(String key) {
		//bar_userWelcome
		String value = words.get(key);
		if (value == null)
			value = key;
		return value;
	}

	/**
	 * Returns the translated string referring to the given key. Replaces the
	 * given arguments.
	 * 
	 * @param string
	 * @param arguments
	 */
	public String string(String key, String... arguments) {
		String value = string(key);
		for(int i = 0; i < arguments.length; i++){
			value = value.replaceFirst("\\$"+i, arguments[i]);
		}
		return value;
	}

	public void load() throws I18NFileLoadingException {
		try {
			List<String> lines = readFile(language.getLocale());
			if (lines == null) {
				throw new I18NFileLoadingException(
						"Unable to load i18n language file[" + language
								+ "]. (File not found)");
			}

			for (String line : lines) {
				if(line.contains("#"))
					line = line.substring(0, line.indexOf("#"));
				String[] laneStrings = line.split("=", 2);
				if (laneStrings.length == 2) {
					String key = laneStrings[0];
					String value = laneStrings[1];
					words.put(key, value);
				}
			}

		} catch (IOException e) {
			throw new I18NFileLoadingException(
					"Unable to load i18n language file[" + language
							+ "]. (IOException)");
		}
	}

	private static List<String> readFile(String language) throws IOException {
		File tfile = new File(I18N_FOLDER + language + ".i18n");
		if (tfile.exists()) {
			return FileUtils.readLines(tfile, "UTF-8");
		}
		return null;
	}

}
